﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Photon.SocketServer;
using Common;
using Common.Tools;
using Common.Model;

using MyGameServer.Manager;
using MyGameServer.Model;
using System.IO;
using System.Xml.Serialization;

namespace MyGameServer.Handler
{
    class StartGameHandler : BaseHandler
    {
        public StartGameHandler()
        {
            OpCode = OperationCode.StartGame;
        }
        public override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters, ClientPeer peer)
        {
            //int readyState = (int)DictTool.GetValue<byte, object>(operationRequest.Parameters, (byte)ParameterCode.StartGame);
            Room room = Functions.GetRoomFromRoomListByPlayerId(MyGameServer.Instance.roomList, peer.uuid);
            //CommonUser user = Functions.GetAvatarUser(room.playerList, peer.uuid);

            //room.gameState = 1;
            room.StartGame();

            for (int i = 0; i < room.playerList.Count; i++)
            {
                int avatarIndex = i;
                room.Draw(avatarIndex);
            }
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);
            room.Draw(0);

            OperationResponse response = new OperationResponse(operationRequest.OperationCode);
            Dictionary<byte, object> data = new Dictionary<byte, object>();
            response.Parameters = data;
            peer.SendOperationResponse(response, sendParameters);

            //广播
            foreach (var ntfPeer in MyGameServer.Instance.peerList)
            {
                if (string.IsNullOrEmpty(ntfPeer.username) == false)
                {
                    bool isInRoom = Functions.IsPlayerInRoom(room, ntfPeer.uuid);
                    if (isInRoom)
                    {
                        EventData ed = new EventData((byte)EventCode.StartGame);
                        Dictionary<byte, object> dataEvent = new Dictionary<byte, object>();
                        
                        string xmlString = Functions.ObjectToXmlString<Room>(room);
                        dataEvent.Add((byte)ParameterCode.StartGame, xmlString);

                        ed.Parameters = dataEvent;
                        ntfPeer.SendEvent(ed, sendParameters);
                    }
                }
            }
        }
    }
}